//
//  SCNWebViewController.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/3/17.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import WebKit

class SCNWebViewController: SCNBaseViewController {

    var webView: WKWebView!
    
    var url: String!
    
    var webTitle: String?
    
    var progressView: UIProgressView!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()


        self.title = webTitle
        
        let url = NSURL(string: self.url)
                
        let request = NSURLRequest(url: url! as URL)
        //获取cookies并放入请求头部
        let userContentController = WKUserContentController()
        
        if let cookies = HTTPCookieStorage.shared.cookies{
        
            let script = getJSCookiesString(cookies: cookies)
            
            let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
            userContentController.addUserScript(cookieScript)
        }
        let webviewConfig = WKWebViewConfiguration()
        webviewConfig.userContentController = userContentController
        

        webView = WKWebView(frame: .zero ,configuration: webviewConfig)
        
        webView.navigationDelegate = self
        
        webView.uiDelegate = self
        
        self.view.addSubview(webView)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        webView.load(request as URLRequest)
        // estimatedProgress 该键值为监听加载进度
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        
        progressView = UIProgressView(frame: CGRect(x: 0, y: SCNConstants.NavigationHeight, width: SCNConstants.SCREENWIDTH, height: 3))
        progressView.progressTintColor = .blue
        progressView.trackTintColor = .clear
        
        view.addSubview(progressView)
        
        progressView.setProgress(0.01, animated: true)
    }

    deinit {
        webView.removeObserver(self,forKeyPath:"estimatedProgress")
    }

}

extension SCNWebViewController: WKUIDelegate, WKNavigationDelegate {
    
    // MARK: - KVO
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {
            
            if let new = change?[.newKey] {
                let value = new as! Float
                
                if (value >= 1) {
                    progressView.setProgress(value, animated: true)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                        self.progressView.progress = 0
                    }
                    
                } else {
                    progressView.setProgress(value, animated: true)
                    
                }
                
            }
        }
        
    }
    
    
    // MARK: - WKNavigationDelegate
    
    /**
     *  页面开始加载时调用
     */
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    /**
     *  当内容开始返回时调用
     */
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    /**
     *  页面加载完成之后调用
     */
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    /**
     *  加载失败时调用
     */
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
    }
    /**
     *  接收到服务器跳转请求之后调用
     */
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    /**
     *  在发送请求之前，决定是否跳转
     */
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        decisionHandler(.allow)
    }
    /**
     *  在收到响应后，决定是否跳转
     */
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        let response: HTTPURLResponse = navigationResponse.response as! HTTPURLResponse
        
        let cookie = HTTPCookie.cookies(withResponseHeaderFields: response.allHeaderFields as! [String : String], for: response.url!)
        
        for tmp in cookie {
            HTTPCookieStorage.shared.setCookie(tmp)
        }
        
        decisionHandler(.allow)
    }
    
    // MARK: 生成 cookie
    // 1、该方法可执行 cookie同步（尝试几种方式）
    public func getJSCookiesString(cookies: [HTTPCookie]) -> String {
        var result = ""
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
        dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
        
        for cookie in cookies {
            HTTPCookieStorage.shared.setCookie(cookie)
            result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
            if let date = cookie.expiresDate {
                result += "expires=\(dateFormatter.string(from: date)); "
            }
            if (cookie.isSecure) {
                result += "secure; "
            }
            result += "'; "
            

        }
        return result
    }
    
    //2、该方法不可执行
    func getScript(cookies: [HTTPCookie]) -> String {
        var cookieDic = [String : String]()
        var cookieValue = ""
        
        
        if let cookies = HTTPCookieStorage.shared.cookies {
            for cookie in cookies {
                cookieDic[cookie.name] = cookie.value
            }
            
            for (k,_) in cookieDic {
                let appen = String(format: "%@=%@",k,cookieDic[k]!)
                cookieValue.append(appen)
            }
        }

        return cookieValue
    }
    //3、该方法不可执行
    func getCookie(url: URL) -> NSURLRequest {
        
        var cookieDic = [String : String]()
        var cookieValue = ""
        
        
        if let cookies = HTTPCookieStorage.shared.cookies {
            for cookie in cookies {
                cookieDic[cookie.name] = cookie.value
            }
            for (k,_) in cookieDic {
                let appen = String(format: "%@=%@",k,cookieDic[k]!)
                cookieValue.append(appen)
            }
            
            let result = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
            result.addValue(cookieValue, forHTTPHeaderField: "Cookie")
            
            return result
            
        }
        
        return NSURLRequest()
        
    }
}











